package com.cruise.h5.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.codingapi.txlcn.tc.annotation.DTXPropagation;
import com.codingapi.txlcn.tc.annotation.LcnTransaction;
import com.cruise.common.mybatis.util.CommonBeanUtil;
import com.cruise.common.web.ex.BizException;
import com.cruise.common.web.result.Result;
import com.cruise.common.web.result.ResultCode;
import com.cruise.common.web.util.WebUtils;
import com.cruise.h5.mapper.PostFileMapper;
import com.cruise.h5.mapper.PostLikeRecordMapper;
import com.cruise.h5.mapper.PostMapper;
import com.cruise.h5.pojo.dto.LikeDTO;
import com.cruise.h5.pojo.dto.PostDTO;
import com.cruise.h5.pojo.dto.PostListDTO;
import com.cruise.h5.pojo.entity.Post;
import com.cruise.h5.pojo.entity.PostFile;
import com.cruise.h5.pojo.entity.PostLikeRecord;
import com.cruise.h5.pojo.vo.PostListVO;
import com.cruise.h5.pojo.vo.UploadFileVO;
import com.cruise.h5.service.PostService;
import com.cruise.h5.util.TimeUtile;
import com.cruise.h5.util.UploadFilesUtil;
import com.cruise.system.userapi.dto.UpdateUserDataCountDTO;
import com.cruise.system.userapi.entity.SysUser;
import com.cruise.system.userapi.feignapi.FeignSystemApi;
import com.google.common.collect.Lists;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author cruise
 * @since 2021-03-25
 */
@Service
@Transactional(rollbackFor = RuntimeException.class)
public class PostServiceImpl extends ServiceImpl<PostMapper, Post> implements PostService {

    @Resource
    private PostMapper postMapper;

    @Resource
    private PostFileMapper postFileMapper;

    @Resource
    private FeignSystemApi feignSystemApi;


    @Resource
    private PostLikeRecordMapper postLikeRecordMapper;

    @Override
    @LcnTransaction(propagation = DTXPropagation.REQUIRED)
    public void post(PostDTO postDTO) {

        Post post = new Post(WebUtils.getUserId(), WebUtils.getUserId(), WebUtils.getUserId());
        BeanUtils.copyProperties(postDTO, post);
        postMapper.insert(post);

        List<PostDTO.PostFileDTO> postFileDTOList = postDTO.getPostFileDTOList();
        if(postFileDTOList.size() > 0){
            for(PostDTO.PostFileDTO postFileDTO : postFileDTOList){
                PostFile postFile = new PostFile();
                BeanUtils.copyProperties(postFileDTO, postFile);
                UploadFileVO uploadFileVO = UploadFilesUtil.generateImage(postFileDTO.getPostFileUrl());
                postFile.setPostFileUrl(uploadFileVO.getFileUrl());
                postFile.setPostId(post.getId());
                postFileMapper.insert(postFile);
            }
        }
        UpdateUserDataCountDTO updateUserDataCountDTO = new UpdateUserDataCountDTO(WebUtils.getUserId(), true);
        updateUserDataCountDTO.setPostCount(1);
        feignSystemApi.updateUserDataCount(updateUserDataCountDTO);

    }


    @Override
    public void like(LikeDTO likeDTO) {

        Integer isLike = likeDTO.getIsLike();
        if(isLike > 0){
            postMapper.like(likeDTO.getId());

            PostLikeRecord postLikeRecord = new PostLikeRecord(WebUtils.getUserId(), likeDTO.getId());
            postLikeRecordMapper.insert(postLikeRecord);
        }else if(isLike < 0){
            postMapper.cancelLike(likeDTO.getId());
            postLikeRecordMapper.delete(new QueryWrapper<PostLikeRecord>().lambda()
                    .eq(PostLikeRecord::getUserId, WebUtils.getUserId())
                    .eq(PostLikeRecord::getPostId, likeDTO.getId()));
        }else {
            throw new BizException(ResultCode.BODY_NOT_MATCH);
        }
    }

    @Override
    public Result<IPage<PostListVO>> postList(PostListDTO postListDTO) {
        if (StringUtils.isEmpty(postListDTO.getUserId())){
            // 如果 userId 为空，默认当前用户
            postListDTO.setUserId(WebUtils.getUserId());
        }
        Page<Post> postPageParam = new Page<>(postListDTO.getCurrent(), postListDTO.getSize());
        Page<Post> postPage =(Page<Post>)postMapper.selectPage(postPageParam , new QueryWrapper<Post>().lambda().eq(Post::getCreateBy, postListDTO.getUserId()).orderByDesc(Post::getCreateDate));
        IPage<PostListVO> postListPageVO = CommonBeanUtil.pageVo(postPage, PostListVO.class);

        // 获取附件
        List<PostListVO> records = postListPageVO.getRecords();
        if(records.size() > 0){
            for(PostListVO postListVO : records){
                List<PostFile> postFileList = postFileMapper.selectList(new QueryWrapper<PostFile>().lambda().eq(PostFile::getPostId, postListVO.getId()).orderByAsc(PostFile::getPostFileOrder));
                List<PostListVO.PostFileVO> transform = Lists.transform(postFileList, (entity) -> {
                    PostListVO.PostFileVO vo = new PostListVO.PostFileVO();
                    BeanUtils.copyProperties(entity, vo);
                    return vo;
                });
                postListVO.setPostFileVOList(transform);

                SysUser sysUser = feignSystemApi.findById(postListVO.getUserId());
                postListVO.setAvatar(sysUser.getAvatar());
                postListVO.setNickname(sysUser.getNickname());
                postListVO.setCreateDateStr(TimeUtile.putDate(postListVO.getCreateDate()));
            }
        }
        return Result.success(postListPageVO);
    }
}
